package cn.shanke.torrentmanagerserver.service;

import cn.shanke.torrentmanagerserver.btclient.model.TmTorrentInfo;
import cn.shanke.torrentmanagerserver.dao.TorrentInClientMapper;
import cn.shanke.torrentmanagerserver.model.TorrentInClient;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service
@Transactional
public class TorrentInClientService extends ServiceImpl<TorrentInClientMapper, TorrentInClient> {

    public List<Map<String, Object>> countClients(String torrentids) {
        return baseMapper.countClients(torrentids);
    }

    @Transactional
    public void bind(Long torrentid, Long clientid, TmTorrentInfo info) {
        QueryWrapper<TorrentInClient> query = new QueryWrapper<>();
        query.lambda().eq(TorrentInClient::getTorrentid, torrentid).eq(TorrentInClient::getClientid, clientid);
        TorrentInClient model = super.getOne(query);
        if (model == null) {
            model = new TorrentInClient();
            model.setTorrentid(torrentid);
            model.setClientid(clientid);
            model.setBtid(info.getId());
            model.setHashstr(info.getHashString());
            super.save(model);
        } else {
            model.setBtid(info.getId());
            model.setHashstr(info.getHashString());
            super.updateById(model);
        }
    }
}
